<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1040" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef">
      <template #billTypeSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" :disabled="isDetail" placeholder="请选择单据类型" readonly @search="billTypeOpen" />
      </template>
      <template #currencySlot="{ model, field }">
        <a-input-search v-model:value="model[field]" :disabled="isDetail" placeholder="请选择币种" readonly @search="open" />
      </template>
      <template #customerSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" :disabled="isDetail" placeholder="请选择客户名称" readonly @search="openCustomer" />
      </template>
      <template #organizationSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" :disabled="isDetail" placeholder="请选择接单组织" readonly @search="openOrganization" />
      </template>
      <template #paymentConditionSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" :disabled="isDetail" placeholder="请选择付款条件" readonly @search="openPaymentCondition(1)" />
      </template>
      <template #accountConditionSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" :disabled="isDetail" placeholder="请选择立账条件" readonly @search="openPaymentCondition(2)" />
      </template>
      <template #shippingPrincipleSlot="{ model, field }">
        <a-input-search
          v-model:value="model[field]"
          :disabled="isDetail"
          placeholder="请选择出货原则"
          readonly
          @search="shippingPrincipleRegModalOpen"
        />
      </template>
      <template #billCodeSlot="{ model, field }">
        <a-input v-model:value="model[field]" placeholder="自动编码" :disabled="isAutoCode === true" />
      </template>
    </BasicForm>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="明细" key="busSaleOrderItem" :forceRender="true">
        <JVxeTable
          @added="added"
          :rowNum="true"
          rowNumKey="rowNum"
          keep-source
          resizable
          ref="busSaleOrderItem"
          :loading="busSaleOrderItemTable.loading"
          :columns="busSaleOrderItemTable.columns"
          :dataSource="busSaleOrderItemTable.dataSource"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
          @removed="removed"
        >
          <template #action="props">
            <a-input-search
              @search="handleView(props)"
              :disabled="formDisabled"
              placeholder="请选择料号"
              readonly
              v-model:value="props.row.materialCode"
            ></a-input-search>
          </template>
          <template #organizationSlot="props">
            <a-input
              @click="organizationHandleView(props)"
              placeholder="请选择生产组织"
              readonly
              v-model:value="props.row.produceOrganizationName"
            ></a-input>
          </template>
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>
    <!-- <template #footer>
      <a-button
        @click="
          reset();
          closeModal();
        "
        >取 消</a-button
      >
      <a-button type="primary" @click="handleSubmit">确 认</a-button>
    </template> -->
  </BasicModal>
  <!-- 币种 -->
  <currencySelectModel @register="regModal" @getSelectResult="handleSuccess" v-bind="getBindValue"></currencySelectModel>
  <!-- 客户 -->
  <customerSelectModel @register="customerRegModal" @getSelectResult="customerHandleSuccess" v-bind="getBindValue"> </customerSelectModel>
  <!-- 接单组织 -->
  <organizationSelectModel
    @register="organizationRegModal"
    @getSelectResult="organizationHandleSuccess"
    v-bind="getBindValue"
  ></organizationSelectModel>
  <!-- 条件 -->
  <paymentConditionSelectModel
    @register="paymentConditionRegModal"
    @getSelectResult="paymentConditionHandleSuccess"
    v-bind="getBindValue"
  ></paymentConditionSelectModel>
  <!-- 料品 -->
  <materialSelectModel
    v-if="openView"
    @handleClose="handleClose"
    @register="materialRegModal"
    @getSelectResult="materialhandleSuccess"
    v-bind="getBindValue"
  >
  </materialSelectModel>
  <!-- 单据类型 -->
  <billTypeSelectModel @register="billTypeRegModal" @getSelectResult="billTypehandleSuccess" v-bind="getBindValue"> </billTypeSelectModel>
  <!-- 收货原则 -->
  <shippingPrincipleSelectModel
    @register="shippingPrincipleRegModal"
    @getSelectResult="shippingPrincipleandleSuccess"
    v-bind="getBindValue"
  ></shippingPrincipleSelectModel>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods';
import { formSchema, busSaleOrderItemColumns } from '../BusSaleOrder.data';
import { saveOrUpdate, busSaleOrderItemList } from '../BusSaleOrder.api';
import currencySelectModel from './currencySelectModel.vue';
import customerSelectModel from './customerSelectModel.vue';
import organizationSelectModel from './organizationSelectModel.vue';
import paymentConditionSelectModel from './paymentConditionSelectModel.vue';
import materialSelectModel from './materialSelectModel.vue';
import billTypeSelectModel from '/@/views/components/billTypeSelectModel.vue';
import { localStorage } from '/@/utils/store/locaStore';
import shippingPrincipleSelectModel from '/@/views/components/shippingPrincipleSelectModel.vue';
import { queryUserOrganization } from '/@/views/system/depart/depart.api';
import { filter, forEach } from '../../../../../utils/helper/treeHelper';

// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const isDetail = ref<boolean>(false);
const formDisabled = ref(false);
const refKeys = ref(['busSaleOrderItem']);
const activeKey = ref('busSaleOrderItem');
const busSaleOrderItem = ref();
const tableRefs = { busSaleOrderItem };
const isAutoCode = ref(true);
const busSaleOrderItemTable = reactive<any>({
  loading: false,
  dataSource: [],
  columns: busSaleOrderItemColumns,
});
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, getFieldsValue, validate }] = useForm({
  labelWidth: 150,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 8 },
});
async function getCurrentDeparts() {
  const result = await queryUserOrganization({});
  return result.list.filter((item) => result.organizationId === item.id)[0];
}
// const busSaleOrderItem =
const userOrganization = reactive({ data: { organizationName: '', id: '' } });
let isAdd = false;
function added({ row }) {
  console.log(row);
  
  isAdd = true;
  let currentMasterData = getFieldsValue();
  const { orderDeliveryDate } = currentMasterData;
  const { organizationName, id } = userOrganization.data;
  busSaleOrderItem.value!.setValues([
    {
      rowKey: row.id,
      values: {
        orderDeliveryDate,
        produceOrganizationId: id,
        produceOrganizationName: organizationName,
        rowNum: row.rowNum
      },
    },
  ]);
}
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  userOrganization.data = await getCurrentDeparts();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  isDetail.value = !!data?.isDetail;
  formDisabled.value = !data?.showFooter;
  if (unref(isUpdate)) {
    isAutoCode.value = true;
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    requestSubTableData(busSaleOrderItemList, { id: data?.record?.id }, busSaleOrderItemTable);
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter });
});

//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);
const [regModal, { openModal }] = useModal();
const [billTypeRegModal, { openModal: openBillTypeModal }] = useModal();
const [shippingPrincipleRegModal, { openModal: openShippingPrincipleRegModal }] = useModal();
const [customerRegModal, { openModal: openCustomerModal }] = useModal();
const [organizationRegModal, { openModal: openOrganizationModal }] = useModal();
const [paymentConditionRegModal, { openModal: openPaymentConditionModal }] = useModal();
const [materialRegModal, { openModal: openMaterialModal }] = useModal();
const [unitRegModal, { openModal: openUnitModal }] = useModal();
//单据类型
function billTypeOpen() {
  openBillTypeModal(true, {
    isUpdate: false,
    showFooter: true,
    tableName: 'bus_sale_order',
  });
}
//打开选择币种
function open() {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择客户
function openCustomer() {
  openCustomerModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择销售组织
function openOrganization() {
  openOrganizationModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择条件
function openPaymentCondition(type) {
  openPaymentConditionModal(true, {
    isUpdate: false,
    showFooter: true,
    type: type,
  });
}
let index: number | null = null;
const openView = ref(true);
let clickRowNum = 0;
//打开选择料品
function handleView(props) {
  console.log('打开料品', props);
  clickRowNum = props.row.rowNum;
  // openView.value = true;
  index = props.params.$rowIndex;
  openMaterialModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开业务组织
function organizationHandleView(props) {
  index = props.params.$rowIndex;
  openOrganizationModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
// 打开选择出货原则
function shippingPrincipleRegModalOpen(props) {
  openShippingPrincipleRegModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}

const getBindValue = Object.assign({}, '');
//币种选择回写
function handleSuccess(val, values) {
  setFieldsValue({
    currencyName: val[0].label,
    currencyId: val[0].value,
  });
}
//客户选择回写
function customerHandleSuccess(val, values) {
  setFieldsValue({
    customerName: val[0].label,
    customerId: val[0].value,
    customerCode: val[0].item.code,
  });
}

// 出货原则回写
function shippingPrincipleandleSuccess(val, values) {
  setFieldsValue({
    shippingPrincipleName: val[0].label,
    shippingPrincipleId: val[0].value,
  });
}
//客户选择回写
function organizationHandleSuccess(val, values) {
  setFieldsValue({
    orderOrganizationName: val[0].label,
    orderOrganizationId: val[0].value,
  });
  if (index != null) {
    busSaleOrderItemTable.dataSource = busSaleOrderItem.value!.getTableData();
    busSaleOrderItemTable.dataSource[index].produceOrganizationName = val[0].label;
    busSaleOrderItemTable.dataSource[index].produceOrganizationId = val[0].value;
  }
}
//条件选择回写
function paymentConditionHandleSuccess(val, values, type) {
  if (type == 1) {
    setFieldsValue({
      paymentConditionName: val[0].label,
      paymentConditionId: val[0].value,
    });
  } else if (type == 2) {
    setFieldsValue({
      accountConditionName: val[0].label,
      accountConditionId: val[0].value,
    });
  }
}
const delRow = reactive<any>({ data: [] });
const removed = (data) => {
  console.log('点击删除');
  delRow.data = data.deleteRows;
};
//料品回写
function materialhandleSuccess(val) {
  openView.value = false;
  if (isAdd) {
    let currentMasterData = getFieldsValue();
    const { orderDeliveryDate } = currentMasterData;
    const { organizationName, id } = userOrganization.data;
    busSaleOrderItemTable.dataSource = busSaleOrderItem.value!.getTableData();
    val.forEach((item,index) => {
      console.log(clickRowNum);
      
      busSaleOrderItemTable.dataSource.push({
        rowNum: clickRowNum+index*10,
        materialId: item.value,
        materialName: item.label,
        materialCode: item.item.code,
        unitId: item.item.stockUnitId,
        unitName: item.item.stockUnitName,
        orderDeliveryDate,
        produceOrganizationId: id,
        produceOrganizationName: organizationName,
      });
    });
    busSaleOrderItemTable.dataSource.forEach((item, index) => {
      if (!item.materialId) {
        busSaleOrderItemTable.dataSource.splice(index, 1);
      }
    });
    busSaleOrderItemTable.dataSource = busSaleOrderItemTable.dataSource.filter(
      (obj, index, self) => index === self.findIndex((o) => o.materialId === obj.materialId && o.stockUnitName === obj.stockUnitName)
    );
    isAdd = false;
  } else {
    busSaleOrderItemTable.dataSource = busSaleOrderItemTable.dataSource.map((item) => {
      console.log('val',val);
      console.log('item',item?.rowNum);
      
      if (clickRowNum === item?.rowNum) {
        return {
          ...item,
          materialId: val[0].value,
          materialName: val[0].label,
          materialCode: val[0].item.code,
          unitId: val[0].item.stockUnitId,
          unitName: val[0].item.stockUnitName,
        };
      } else {
        return {
          ...item
        }
      }
    });
    console.log(busSaleOrderItemTable.dataSource);
  }
  setTimeout(() => {
    openView.value = true;
  });
  // console.log('删除的数据',delRow.data);
  // const newIndex: any = [];
  // val.forEach((item, index) => {
  //   delRow.data.forEach((items) => {
  //     if (item.value === items?.materialId) {
  //       newIndex.push(index);
  //     }
  //   });
  // });
  // delRow.data = []
  // newIndex.sort((a, b) => b - a);
  // newIndex.forEach((index) => {
  //   val.splice(index, 1);
  // });
  // const tempArray = val.map((item) => {
  //   return {
  //     materialId: item.value,
  //     materialName: item.label,
  //     materialCode: item.item.code,
  //     unitId: item.item.stockUnitId,
  //     unitName: item.item.stockUnitName,
  //   };
  // });
  // const { orderDeliveryDate } = currentMasterData;
  // const { organizationName, id } = userOrganization.data;
  // busSaleOrderItem.value!.setValues([
  //   {
  //     rowKey: row.id,
  //     values: {
  //       orderDeliveryDate,
  //       produceOrganizationId: id,
  //       produceOrganizationName: organizationName,
  //     },
  //   },
  // ]);
  // console.log('去重', uniqueArray);
  // console.log(busSaleOrderItemTable.dataSource);

  // busSaleOrderItemTable.dataSource.push(val)
  // busSaleOrderItemTable.dataSource[index].materialName = val[0].label;
  // busSaleOrderItemTable.dataSource[index].materialId = val[0].value;
  // // 自动带出单位
  // busSaleOrderItemTable.dataSource[index].unitId = val[0].item.stockUnitId;
  // busSaleOrderItemTable.dataSource[index].unitName = val[0].item.stockUnitName;
  // console.log("busSaleOrderItem.value",options);
  // let tempArr = [];
  // options.forEach(val => {
  //   tempArr.push({
  //     materialName : val.item.name,
  //     materialId : val.item.id,
  //     unitId : val.item.stockUnitId,
  //     unitName : val.item.stockUnitName
  //   })
  // })
  // busSaleOrderItem.value = tempArr;
  // console.log(busSaleOrderItem.value);

  // // return
  // busSaleOrderItemTable.dataSource = busSaleOrderItem.value
  // busSaleOrderItemTable.dataSource[index].materialName = val[0].label;
  // busSaleOrderItemTable.dataSource[index].materialId = val[0].value;
  // // 自动带出单位
  // busSaleOrderItemTable.dataSource[index].unitId = val[0].item.stockUnitId;
  // busSaleOrderItemTable.dataSource[index].unitName = val[0].item.stockUnitName;
}
function handleClose() {
  openView.value = false;
  setTimeout(() => {
    openView.value = true;
  });
}
//单据类型回写
function billTypehandleSuccess(val, values) {
  isAutoCode.value = val[0].item.codingScheme == 2;
  setFieldsValue({
    billTypeName: val[0].label,
    billTypeId: val[0].value,
    billCode: isAutoCode.value ? '自动编码' : '',
  });
}

//设置标题
const title = computed(() => (unref(isDetail) ? '详情' : !unref(isUpdate) ? '新增' : '编辑'));

async function reset() {
  await resetFields();
  activeKey.value = 'busSaleOrderItem';
  busSaleOrderItemTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  const str = 'row';
  allValues.tablesValue[0].tableData.map((item) => {
    if (item.id.indexOf(str) != -1) {
      delete item.id;
    }
  });

  let main = Object.assign({}, allValues.formValue);
  return {
    ...main, // 展开
    busSaleOrderItemList: allValues.tablesValue[0].tableData,
  };
}
//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });
    //提交表单
    localStorage.remove('saleDepartId');

    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>
